import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class StorageService extends GetxService {
  static StorageService get to => Get.find();
  late final SharedPreferences _prefs;

  Future<StorageService> init() async {
    _prefs = await SharedPreferences.getInstance();
    return this;
  }

  // Token管理
  String? get token => _prefs.getString('token');
  Future<void> setToken(String token) => _prefs.setString('token', token);
  Future<void> removeToken() => _prefs.remove('token');

  // 用户信息管理
  String? get userPhone => _prefs.getString('userPhone');
  String? get userEmail => _prefs.getString('userEmail');
  String? get userId => _prefs.getString('userId');

  Future<void> saveUser({String? id, String? phone, String? email}) async {
    if (id != null) await _prefs.setString('userId', id);
    if (phone != null) await _prefs.setString('userPhone', phone);
    if (email != null) await _prefs.setString('userEmail', email);
  }

  Future<void> clearUser() async {
    await _prefs.remove('userId');
    await _prefs.remove('userPhone');
    await _prefs.remove('userEmail');
  }

  // 清除所有数据
  Future<void> clearAll() async {
    await removeToken();
    await clearUser();
  }
  
  // 检查是否登录
  bool get isLoggedIn => token != null;
}